package org.cloud.admin.auth.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.cloud.admin.auth.holder.AppHolder;
import org.cloud.admin.auth.service.SysUserRoleService;
import org.cloud.admin.auth.service.SysUserService;
import org.cloud.common.exception.SlothCloudException;
import org.cloud.common.util.DigestUtils;
import org.cloud.module.common.dao.SysUserDao;
import org.cloud.module.common.entity.SysUserEntity;
import org.cloud.module.common.model.Query;
import org.cloud.module.common.util.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 系统用户
 * @author wangyuan
 * @since 2019年6月16日 上午12:39:48
 *
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
	
	@Autowired
	private SysUserRoleService sysUserRoleService;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		String username = (String)params.get("username");
		
		IPage<SysUserEntity> page = new Query<SysUserEntity>().getPage(params);
		
		QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
		
		queryWrapper.select("id", "username", "user_type", "enabled", "created_time");
		
		queryWrapper.like(StringUtils.isNotBlank(username),"username", username);

		page = this.page(page, queryWrapper);
		
		return new PageUtils(page);
	}

	@Override
	public List<String> queryAllPerms(Long userId) {
		return baseMapper.queryAllPerms(userId);
	}

	@Override
	public List<Long> queryAllMenuId(Long userId) {
		return baseMapper.queryAllMenuId(userId);
	}

	@Override
	public SysUserEntity queryByUserName(String username) {
		QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
		
		queryWrapper.eq("username", username);
		
		return getOne(queryWrapper);
	}

	@Override
	public void saveUser(SysUserEntity user) {
		//sha256加密
		String salt = RandomStringUtils.randomAlphanumeric(20);
		try {
			user.setPassword(DigestUtils.sha256Hex(user.getPassword(), salt));
		} catch (Exception e) {
			throw new SlothCloudException("密码加密失败", e);
		}
		user.setSalt(salt);
		this.save(user);
		
		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getId(), user.getRoleIdList());
	}

	@Override
	public void update(SysUserEntity user) {
	    SysUserEntity oldUser = getById(user.getId());
	    
	    oldUser.setUsername(user.getUsername());
	    oldUser.setUserType(user.getUserType());
	    oldUser.setEnabled(user.getEnabled());
	    oldUser.setUpdatedUser(String.valueOf(AppHolder.getLoginedUserId()));
	    if(StringUtils.isNotBlank(user.getPassword())){
	        try {
	            oldUser.setPassword(DigestUtils.sha256Hex(user.getPassword(), oldUser.getSalt()));
            } catch (Exception e) {
                throw new SlothCloudException("密码加密失败", e);
            }
		}
		this.updateById(oldUser);
		
		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getId(), user.getRoleIdList());
	}

	@Override
	public void deleteBatch(Long[] userId) {
	    List<Long> userIds = Arrays.asList(userId);
		this.removeByIds(userIds);
		
		sysUserRoleService.deleteBatchByUserIds(userId);
	}

	@Override
	public boolean updatePassword(Long userId, String password, String newPassword) {
		SysUserEntity userEntity = new SysUserEntity();
		userEntity.setPassword(newPassword);
		userEntity.setUpdatedUser(String.valueOf(AppHolder.getLoginedUserId()));
		return this.update(userEntity, new QueryWrapper<SysUserEntity>().eq("id", userId).eq("password", password));
	}
}